import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import { fetchValidation } from '@/utils';
import { queryRechargeMoneyList, rechargeMoney, queryOrderStatus } from './service';

import { TableListData } from './data';

export interface StateType {
  rechargelist: TableListData;
  orderInfo: any;
  orderResults: boolean;
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & {
    select: <T>(func: (state: StateType) => T) => T;
  }
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetch: Effect;
    recharge: Effect;
    orderStatus: Effect;
  };
  reducers: {
    save: Reducer;
    createSure: Reducer;
    status: Reducer;
    init: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'rechargeMoney',

  state: {
    rechargelist: {
      list: [],
      count: 0,
    },
    orderInfo: {
      createOrder: false,
    },
    orderResults: false,
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryRechargeMoneyList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: response.body,
      });
    },

    * recharge({ payload }, { call, put }) {
      const response = yield call(rechargeMoney, payload);
      const data = fetchValidation(response);
      if (data) {
        response.body.createOrder = true;
        yield put({
          type: 'createSure',
          payload: response.body,
        });
      }
    },

    * orderStatus({ payload: { orderValues, searchValues } }, { call, put }) {
      const response = yield call(queryOrderStatus, orderValues);
      const data = fetchValidation(response);
      if (data) {
        const { trade_status } = response.body;
        switch (trade_status) {
          case 13102: message.error('支付未完成'); break;
          case 13104: message.error('支付失败'); break;
          case 13103: message.success('充值成功'); break;
          default: return null;
        }
        yield put({
          type: 'status',
          payload: response.body,
        });
        yield put({
          type: 'fetch',
          payload: searchValues,
        });
      }
      return null;
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        rechargelist: action.payload,
      };
    },

    createSure(state, action) {
      return {
        ...state,
        orderInfo: action.payload,
      };
    },

    status(state, action) {
      return {
        ...state,
        orderResults: true,
      };
    },

    init(state, action) {
      return {
        ...state,
        orderResults: false,
        orderInfo: {
          createOrder: false,
        },
      };
    },
  },
};

export default Model;
